<script setup lang="ts">
import { reactive } from 'vue'
// import { RegisterUser } from '@/types/data'
import type { RegisterUser } from '@/types/data'

import { showSuccessToast, showFailToast } from 'vant'

import { register } from '@/api/user'
import { useRouter } from 'vue-router'

// import type { AxiosError } from 'axios'

// import { Notify } from 'vant'

const router = useRouter()

// 用户表单
const UserForm = reactive<RegisterUser>({
  username: '',
  password: '',
  confirmpassword: ''
})
const onSubmit = async (values: RegisterUser) => {
  console.log(values)
  try {
    delete values.confirmpassword //删除确认密码
    await register(values)
    showSuccessToast('注册成功')
    router.push('/login')
  } catch (error) {
    // const e = error as AxiosError
    console.log(error)
    showFailToast('注册失败')
  }
}
</script>
<template>
  <div>
    <!-- <van-button type="primary">注册</van-button> -->
    <van-nav-bar title="注册" />
    <van-form @submit="onSubmit">
      <van-cell-group inset>
        <van-field
          v-model="UserForm.username"
          name="username"
          label="用户名"
          placeholder="请输入用户名"
          :rules="[
            { required: true, message: '请填写用户名' },
            {
              pattern: /^\w{6,16}$/,
              message: '用户名只能为6到16位的字母数字或者下划线'
            }
          ]"
        />
        <van-field
          v-model="UserForm.password"
          type="password"
          name="password"
          label="密码"
          placeholder="密码"
          :rules="[
            { required: true, message: '请填写密码' },
            {
              pattern: /^\w{6,16}$/,
              message: '密码的长度为6-16位'
            }
          ]"
        />
        <van-field
          v-model="UserForm.confirmpassword"
          name="confirmpassword"
          type="password"
          label="重复密码"
          placeholder="再次输入密码"
          :rules="[{ required: true, message: '请再次输入密码' }, 
          {
               validator(value: string){
              if(value!== UserForm.password) return false
              return true // 成功校验
            },
            message: '两次输入密码必须一致'
        }]"
        />
      </van-cell-group>
      <div style="margin: 16px">
        <van-button round block type="primary" native-type="submit"> 注册 </van-button>
      </div>
      <van-row justify="end" style="margin-right: 20px">
        <router-link class="link" to="/login">已有账号?去登录</router-link>
      </van-row>
    </van-form>
  </div>
</template>

<style></style>
